<template>
  <span>

    <el-badge v-if="theme.showNotice" :value="badge">
      <vab-icon icon="notification-line" @click="showLog"/>
    </el-badge>
    <el-dialog append-to-body title="任务日志" :visible.sync="dialogVisible" width="60%">
      <el-tabs v-model="tabQueueCode" class="demo-tabs"  type="border-card" >
        <el-tab-pane v-for="(item, index) in current_do" :key="index" :name="item.code">
          <template #label>
            <span class="custom-tabs-label">
              <el-icon><calendar /></el-icon>
              <span>{{item.title}}</span>
            </span>
          </template>
          <p>任务命令：{{item.command}}</p>
          <p>任务编号：{{item.code}}</p>
          <p>执行时间：{{item.exec_time}}</p>
          <p>任务进度：{{item.progress.message}}</p>
          <el-progress :percentage="item.progress.progress || 0"/>
          <div :ref="'logContainer'+item.code" style="background:#393d49!important;width:100%;padding:20px;margin:20px 0px;color:#fff;height:200px;overflow-y:auto;" >
            <p v-for="(item2, index2) in item.history" :key="index2" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
              <!-- {{item2.datetime}}:{{item2.message}} -->
              {{item2}}
            </p>
          </div>

        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button @click="dialogVisible = false">关闭</el-button> -->
          <el-button type="primary" @click="dialogVisible = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </span>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { translateTitle } from '@/utils/i18n'
  import { getList, progress } from '@/api/notice'

  export default {
    name: 'VabNotice',
    data() {
      return {
        dialogVisible: false,
        wait_do: [],
        current_do: [],
        list: [],
        tabQueueCode: "",
        logInfo: {},
        badge: null,
        activeName: 'notice',
        websocket: null, // 添加 WebSocket 实例
        intervalId: null, // 添加轮询请求的定时器 ID
      }
    },
    computed: {
      ...mapGetters({
        theme: 'settings/theme',
      }),
    },
    watch: {
      async tabQueueCode(val){
        console.log(val)
        this.sendMessage('{"type":"queue","logFile":"1","queueId":"'+val+'"}')
        if(val && val != 0){
          console.log(val)
          // 变化以后，采用轮训的方式获取日志
          // let {data} = await progress(val)
          // console.log(data)
          // 停止之前的轮询请求
          if (this.intervalId) {
            clearInterval(this.intervalId)
          }
          var self = this;
          // 启动新的轮询请求
          this.intervalId = setInterval(async () => {
            let { data } = await progress(val)
            data.progress = parseFloat(data.progress)
            self.current_do.forEach((item, index) => {
              if (item.code == val) {
                self.$set(self.current_do[index], 'progress', data)
              }
            })

            // console.log(self.current_do)
          }, 2000) // 每隔 5 秒轮询一次
        }
      }
    },
    created() {
      this.$nextTick(() => {
        if (this.theme.showNotice) this.fetchData()

        this.initWebSocket() // 初始化 WebSocket 连接
      })
    },
    methods: {
      translateTitle,
      tabChange() {
        console.log('tabChange222')
        // console.log(e)
      },
      syncProgress(data) {
        progress(data)
      },  
      handleClick() {
        this.fetchData()
      },

      initWebSocket() {
        this.websocket = new WebSocket('ws://192.168.31.200:8080') // 替换为你的 WebSocket 服务器 URL

        this.websocket.onopen = () => {
          console.log('WebSocket connection opened')
        }
        var self = this;
        this.websocket.onmessage = (event) => {
          // console.log('WebSocket message received:', event.data)
          // 处理接收到的消息
          var message = JSON.parse(event.data)
          // console.log(message)
          if(!this.logInfo[message.queueId]){
            this.logInfo[message.queueId] = []
          }

          self.current_do.forEach((item, index) => {
            if (item.code == message.queueId) {




              // self.$set(self.current_do[index], 'progress', message.log)  self.current_do[index], 'progress'是列表，尾部插入日志
              self.current_do[index].history.push(message.log)
            }
          })

          const logContainer = this.$refs['logContainer' + message.queueId][0]
          if (logContainer) {
            logContainer.scrollTop = logContainer.scrollHeight
          }

        }

        this.websocket.onclose = () => {
          console.log('WebSocket connection closed')
        }

        this.websocket.onerror = (error) => {
          console.error('WebSocket error:', error)
        }
      },


      sendMessage(message) {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
          this.websocket.send(message)
          console.log('Message sent:', message)
        } else {
          console.error('WebSocket is not open')
        }
      },


      showLog() {
        // this.sendMessage('{"type":"queue","logFile":"1","queueId":"'+row.code+'"}')
        // this.$baseMessage('查看日志', 'success', 'vab-hey-message-success')
        this.dialogVisible = true
      },


      handleClearNotice() {
        this.badge = null
        this.list = []
        this.$baseMessage('清空消息成功', 'success', 'vab-hey-message-success')
      },
      async fetchData() {
        let {data} = await getList()

        this.wait_do = data.wait_do
        var current_do = data.current_do
        current_do.forEach((item, index) => {
          current_do[index]['progress'] = {message: '等待执行', progress: 0}
          current_do[index]['history'] = []
        })
        console.log(current_do)
        this.current_do = current_do;
        this.badge = data.current_do.length + data.wait_do.length 
      },
    },
  }
</script>

<style lang="scss" scoped>
  :deep() {
    .el-tabs__active-bar {
      min-width: 28px;
    }
  }

  .notice-list {
    height: 29vh;

    ul {
      padding: 0 15px 0 0;
      margin: 0;

      li {
        display: flex;
        align-items: center;
        padding: 10px 0 10px 0;

        :deep() {
          .el-avatar {
            flex-shrink: 0;
            width: 50px;
            height: 50px;
            border-radius: 50%;
          }
        }

        span {
          margin-left: 10px;
        }
      }
    }
  }

  .notice-clear {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0 0 0;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
    border-top: 1px solid #e8eaec;

    i {
      margin-right: 3px;
    }
  }
</style>
